<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdate ? t('common.edit') : t('common.create')"
    @register="register"
    @ok="handleSubmit"
    :destroyOnClose="true"
    :minHeight="500"
    :width="600"
  >
    <BasicForm @register="registerForm" />
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">
          {{ t('common.create') }}
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: t('common.confirmDelete'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
  </BasicModal>
  <!-- 码段定义弹窗 -->
  <CodeSettingModal
    @register="registerCodeSettingModal"
    @updateTable="handleUpdateTable"
    @addTable="handleAddTable"
  />
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { getCountSettingForm, getCounterSettingModalColumns } from './data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { addCodeTypeList, updateCodeTypeList } from '/@/api/demo/system';

  import CodeSettingModal from './codeDefined.vue';

  const isUpdate = ref<boolean>(false);
  const dataList = ref<any[]>([]);
  const { t } = useI18n();
  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);

  // 新增
  const handleCreate = () => {
    openCodeSettingModal(true, { isUpdate: false });
  };

  // 修改
  const handleEdit = (record: Recordable) => {
    openCodeSettingModal(true, { isUpdate: true, record: record });
  };

  // 删除
  const handleDelete = (record: Recordable) => {
    dataList.value = dataList.value.filter((item) => item.index !== record.index);
    createMessage.success(t('common.delSuccessText'));
  };

  // 修改表格
  const handleUpdateTable = (values: any) => {
    const index = values.index;
    for (var i = 0; i < dataList.value.length; i++) {
      if (dataList.value[i].index === index) {
        dataList.value[i].tiPDMType = values.tiPDMType;
        dataList.value[i].tiPDMValue = values.tiPDMValue;
        break;
      }
    }
    createMessage.success(t('common.saveSuccess'));
    const newArr = {
      remark: dataList.value.map((item) => `[${item.tiPDMType}:${item.tiPDMValue}]`).join(''),
    };
    setFieldsValue(newArr);
  };
  // 新增表格
  const handleAddTable = (values: any) => {
    dataList.value.push(values);
    dataList.value = dataList.value.map((item, index) => {
      item.index = index + 1;
      return item;
    });
    createMessage.success(t('common.saveSuccess'));
    const newArr = {
      remark: dataList.value.map((item) => `[${item.tiPDMType}:${item.tiPDMValue}]`).join(''),
    };
    setFieldsValue(newArr);
  };

  // 提交
  const handleSubmit = async () => {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      values.mdList = dataList.value;
      if (unref(isUpdate)) await updateCodeTypeList(values);
      else await addCodeTypeList(values);
      closeModal();
      emit('success');
      createMessage.success(t('common.saveSuccess'));
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    dataList.value = [];
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setFieldsValue(data.record);
      dataList.value = data.record.mdList;
    }
  });

  // 属性详情
  const [registerForm, { validate, resetFields, setFieldsValue }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
    schemas: getCountSettingForm(),
    showResetButton: false,
    showSubmitButton: false,
  });

  // 初始化表格
  const [registerTable] = useTable({
    titleHelpMessage: 'countAdd',
    columns: getCounterSettingModalColumns(),
    showTableSetting: true,
    bordered: true,
    maxHeight: 300,
    dataSource: dataList,
    rowKey: 'index',
    actionColumn: {
      width: 80,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 码段定义弹窗
  const [registerCodeSettingModal, { openModal: openCodeSettingModal }] = useModal();
</script>
